package com.ziq.zcamp.community

import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.ScreenUtils
import com.facebook.drawee.backends.pipeline.Fresco
import com.ziq.base.base.BaseFragment
import com.ziq.base.extension.binding
import com.ziq.base.extension.click
import com.ziq.base.extension.dp
import com.ziq.base.extension.launchWithTry
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.post.PostingDetail
import com.ziq.zcamp.databinding.FragmentCommunityRecommendBinding
import com.ziq.zcamp.extension.getValue
import com.ziq.zcamp.manager.*
import com.ziq.zcamp.mine.PersonalHomePageActivity
import com.ziq.zcamp.post.PostingAdapter
import com.ziq.zcamp.view.StatusView
import com.ziq.zcamp.view.layoutmanager.CustomStaggeredGridLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import kotlin.math.abs

@AndroidEntryPoint
class CommunityRecommendFragment : BaseFragment(R.layout.fragment_community_recommend){

    val mViewModel: CommunityRecommendViewModel by viewModels()
    private val binding : FragmentCommunityRecommendBinding? by binding()

    var adapter: CommunityPostingAdapter? = null
    var itemWidth:Int = 0
    val refreshInterval = 50 * 60 * 1000L

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.root

        itemWidth = (ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_24)) / 2
        binding?.recycleView?.layoutManager = CustomStaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        adapter = CommunityPostingAdapter(requireContext(), lifecycle, itemWidth)
        binding?.recycleView?.adapter = adapter
        binding?.recycleView?.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                val pos = parent.getChildAdapterPosition(view)
                if (pos in 0..1 ){
                    outRect.top = 8.dp
                }else{
                    outRect.top = 0
                }
            }
        })
        binding?.recycleView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (Fresco.hasBeenInitialized() && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Fresco.getImagePipeline().resume()//恢复加载图片
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if(abs(dy) > 25){
                    if(Fresco.hasBeenInitialized() && !Fresco.getImagePipeline().isPaused){
                        Fresco.getImagePipeline().pause()// 暂停图片请求
                    }
                } else if(abs(dy) < 5){
                    if(Fresco.hasBeenInitialized() && Fresco.getImagePipeline().isPaused){
                        Fresco.getImagePipeline().resume()//恢复加载图片
                    }
                }
            }
        })
        adapter?.setAction(object : PostingAdapter.PostingAdapterAction {
            override fun itemClick(item: PostingDetail) {
                GlobalContextManager.getCurrentActivity()?.let {
                    PrivacyManager.checkPrivacy(it, action = {
                        PostManager.navigateToDetailActivity(
                            this@CommunityRecommendFragment.requireActivity(),
                            item
                        )
                    })
                }
            }

            override fun userInfoClick(item: PostingDetail) {
                GlobalContextManager.getCurrentActivity()?.let {
                    PrivacyManager.checkPrivacy(it, action = {
                        PersonalHomePageActivity.open(this@CommunityRecommendFragment.requireContext(), item.user?.uid?:0)
                    })
                }
            }
        })

        UserManager.instance.postingLike.observe(viewLifecycleOwner, Observer {
            adapter?.notifyDataSetChanged()
        })

        DataManager.postingVersion.observe(viewLifecycleOwner, Observer<Int> {
            binding?.recycleView?.scrollToPosition(0)
            mViewModel.onRefresh()
        })

        mViewModel.statusShow.observe(viewLifecycleOwner, Observer<Int> {
            when(it){
                StatusView.IDLE -> {
                    binding?.statusView?.setStatus(StatusView.IDLE)
                }
                StatusView.LOADING -> {
                    binding?.statusView?.setStatus(StatusView.LOADING)
                }
                StatusView.NO_DATA -> {
                    binding?.statusView?.setStatus(StatusView.NO_DATA,
                        isCenter = false,
                        marginTop = 60.dp,
                        imgSrc = R.drawable.pic_no_content_camp,
                        imgWidth = 235.dp,
                        imgHeight = 151.dp,
                        msg = "暂无内容～",
                    )
                }
                StatusView.NET_ERROR -> {
                    binding?.statusView?.setStatus(StatusView.NET_ERROR, isCenter = false, marginTop = 130.dp, updateActionBtn = { btn ->
                        btn.click {
                            mViewModel.onRefresh(true)
                            CampLifeManager.requestMyCampData()
                        }
                    })
                }
            }
        })
        mViewModel.listRequestFinished.observe(viewLifecycleOwner, Observer<Boolean> {
            if(it == true){
                binding?.refreshLayout?.finishRefresh()
                binding?.refreshLayout?.finishLoadMore()
            }
        })
        mViewModel.listHasMore.observe(viewLifecycleOwner, Observer<Boolean> {
            if(it == true){
                binding?.refreshLayout?.resetNoMoreData()
            } else {
                binding?.refreshLayout?.setNoMoreData(true)
            }
        })

        mViewModel.list.observe(viewLifecycleOwner) {
            if (PostManager.subjectList.value.isNullOrEmpty()
                || (PostManager.subjectList.value?.size?: 0) < 2 ){
                val num = CampLifeManager.myCampData.getValue()?.camping_count?:0
                adapter?.setCampLifeData(mutableListOf(num))
            }
            adapter?.setData(it)
        }

        mViewModel.bannerList.observe(viewLifecycleOwner) {
            adapter?.setBannerData(it)
        }

        binding?.refreshLayout?.setOnRefreshListener {
            mViewModel.onRefresh(false)
            PostManager.requestSubject()
            CampLifeManager.requestMyCampData()
        }

        PostManager.subjectList.observe(viewLifecycleOwner){
            if (it.isNullOrEmpty() || it.size < 2){
                adapter?.setCampLifeData(mutableListOf(1))
            }else{
                adapter?.setCampLifeData(null)
            }
        }

        launchWithTry(whenTry = {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                CampLifeManager.myCampData.collect{
                    if (PostManager.subjectList.value.isNullOrEmpty()
                        || (PostManager.subjectList.value?.size?: 0) < 2 ){
                        adapter?.setCampLifeData(mutableListOf(it.camping_count?:0))
                    }
                }
            }
        })

        binding?.refreshLayout?.setOnLoadMoreListener {
            mViewModel.onLoadMore()
        }
        mViewModel.onRefresh(true)
    }

    override fun onResume() {
        super.onResume()
        DataManager.changeCommunityPostingBtnShow(true)
        if(mViewModel.lastRefreshTime > 0 && System.currentTimeMillis() - mViewModel.lastRefreshTime > refreshInterval){
            mViewModel.onRefresh(true)
        }
    }

}